package com.ai.chinamobileai.config;

import com.ai.chinamobileai.domain.Conversation;
import com.ai.chinamobileai.mapper.ConversationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.List;

public class MySqlMemory implements ChatMemory {

    @Autowired
    private ConversationMapper conversationMapper;
    @Override
    public void add(String conversationId, List<Message> messages) {
        for (Message message : messages) {
            Conversation conversation = Conversation.builder()
                    .conversationId(conversationId)
                    .message(message.getText())
                    .type(message.getMessageType().getValue())
                    .createTime(LocalDateTime.now())
                    .build();
            conversationMapper.insert(conversation);
        }
    }

    @Override
    public List<Message> get(String conversationId) {
        List<Conversation> conversations = conversationMapper.selectList(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
        List<Message> list = conversations.stream().map(r -> {
                    Message message = null;
                    if (MessageType.ASSISTANT.getValue().equals(r.getType())) {
                        message = new AssistantMessage(r.getMessage());
                    } else if (MessageType.USER.getValue().equals(r.getType())) {
                        message = new AssistantMessage(r.getMessage());
                    }
                    return message;
                }
        ).toList();
        return list;
    }

    @Override
    public void clear(String conversationId) {
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
    }

    }

